package com.niodata.dp.plugin.core;

import java.util.Iterator;
import java.util.ServiceLoader;

public abstract class AbstractDpTaskPlugin<I extends Input, O extends Output> implements DpTaskPlugin {

  private PluginContext pluginContext;

  public AbstractDpTaskPlugin() {
    this.init();
  }

  protected void beforeRun() {
    //record runtime config
  }

  protected void afterSuccess() {
    //nothing to do
  }

  protected void afterFailed() {

  }

  protected void init() {
    try {
      ServiceLoader<PluginContextFactory> loader = ServiceLoader.load(PluginContextFactory.class);
      Iterator<PluginContextFactory> iterator = loader.iterator();
      PluginContextFactory contextFactory = iterator.next();
      pluginContext = contextFactory.getOrCreateContext(this.getClass());
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }

  @Override
  public PluginContext getContext() {
    return this.pluginContext;
  }

  public I getConfig() {
    return (I) this.pluginContext.getConfig();
  }

}
